package com.google.denta.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.Configuration;

import com.google.denta.dao.PaginatorDao;
import com.google.denta.utils.Pages;

public class PaginatorServiceImpl<T> implements PaginatorService<T> {
    private PaginatorDao<T> paginatorDao;

    private Configuration conf;

    /**
     * Setter for configuration dao.
     * @param conf
     *            the conf to set
     */
    public void setConf(Configuration conf) {
        this.conf = conf;
    }

    /**
     * @param paginatorDao
     *            the paginatorDao to set
     */
    public final void setPaginatorDao(PaginatorDao<T> paginatorDao) {
        this.paginatorDao = paginatorDao;
    }


    public void setOptions(Map<String, Object> map, final Long page, final String search,
            final String asc, final String desc) {
        Pages p = new Pages(this.conf.getLong("employees.on.page"));
        map.put("lines", p.lines());
        map.put("offset", p.offset(page));
        map.put("asc", asc);
        map.put("desc", desc);
        if (search != null && !"".equals(search)) {
            map.put("search", "%" + search.toUpperCase() + "%");
        } else {
            map.put("search", null);
        }
    }

    public List<T> getCurrentPage(String sqlMap, Map<String, Object> map) {
        return paginatorDao.findAll(sqlMap, map);
    }

    public Long countPages(String sqlMap, Map<String, Object> map) {
        Pages p = new Pages((Long) map.get("lines"));
        return p.count(paginatorDao.countAll(sqlMap, map));
    }


}
